﻿
Option Compare Binary
Option Infer On
Option Strict On
Option Explicit On

Imports LullabyFullDeCaixa.Web
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Imports System.Data
Imports System.Linq
Imports System.ServiceModel.DomainServices.EntityFramework
Imports System.ServiceModel.DomainServices.Hosting
Imports System.ServiceModel.DomainServices.Server


'Implementa la lógica de la aplicación mediante el contexto LullabyEntities.
' TODO: agregue la lógica de su aplicación a estos métodos o en métodos adicionales.
' TODO: aplique la autenticación (Windows/ASP.NET Forms) y quite las marcas de comentario de lo siguiente para deshabilitar el acceso anónimo
' Considere además la posibilidad de agregar roles para restringir el acceso según necesidad.
'<RequiresAuthentication> _
<EnableClientAccess()>  _
Public Class LullabyDomainService
    Inherits LinqToEntitiesDomainService(Of LullabyEntities)
    Implements ApplicationServices.IAuthentication(Of User)

    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'Hostals'.
    Public Function GetHostals() As IQueryable(Of Hostal)
        Return Me.ObjectContext.Hostals
    End Function

    Public Sub InsertHostal(ByVal hostal As Hostal)
        If ((hostal.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(hostal, EntityState.Added)
        Else
            Me.ObjectContext.Hostals.AddObject(hostal)
        End If
    End Sub

    Public Sub UpdateHostal(ByVal currentHostal As Hostal)
        Me.ObjectContext.Hostals.AttachAsModified(currentHostal, Me.ChangeSet.GetOriginal(currentHostal))
    End Sub

    Public Sub DeleteHostal(ByVal hostal As Hostal)
        If ((hostal.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(hostal, EntityState.Deleted)
        Else
            Me.ObjectContext.Hostals.Attach(hostal)
            Me.ObjectContext.Hostals.DeleteObject(hostal)
        End If
    End Sub

    Public Function GetThingsToDoCategories() As IQueryable(Of ThingsToDoCategory)
        Return Me.ObjectContext.ThingsToDoCategories
    End Function

    Public Sub InsertThingsToDoCategory(ByVal ThingsToDoCategory As ThingsToDoCategory)
        If ((ThingsToDoCategory.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(ThingsToDoCategory, EntityState.Added)
        Else
            Me.ObjectContext.ThingsToDoCategories.AddObject(ThingsToDoCategory)
        End If
    End Sub

    Public Sub UpdateThingsToDoCategory(ByVal currentThingsToDoCategory As ThingsToDoCategory)
        Me.ObjectContext.ThingsToDoCategories.AttachAsModified(currentThingsToDoCategory, Me.ChangeSet.GetOriginal(currentThingsToDoCategory))
    End Sub

    Public Sub DeleteThingsToDoCategory(ByVal ThingsToDoCategory As ThingsToDoCategory)
        If ((ThingsToDoCategory.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(ThingsToDoCategory, EntityState.Deleted)
        Else
            Me.ObjectContext.ThingsToDoCategories.Attach(ThingsToDoCategory)
            Me.ObjectContext.ThingsToDoCategories.DeleteObject(ThingsToDoCategory)
        End If
    End Sub

    Public Function GetThingsToDo() As IQueryable(Of ThingToDo)
        Return Me.ObjectContext.ThingsToDo
    End Function

    Public Function GetThingsToDoByHostalCategoriaUrgenciaEstat(IdHostal As Integer, IdCategoria As Integer, IdUrgencia As Integer, Realitzada As Integer) As IQueryable(Of ThingToDo)
        Dim vRealitzada As Boolean? = Nothing
        If Realitzada >= 0 Then vRealitzada = CBool(IIf(Realitzada = 0, False, True))

        Return (From T As ThingToDo In Me.ObjectContext.ThingsToDo _
        Where _
            (IdHostal = -1 OrElse T.IdHostal = IdHostal) _
            AndAlso (IdCategoria = -1 OrElse T.IdCategoria = IdCategoria) _
            AndAlso (IdUrgencia = -1 OrElse T.Urgencia = IdUrgencia) _
            AndAlso (Not vRealitzada.HasValue OrElse T.Realizada = vRealitzada.Value) _
            ).AsQueryable()
        Return Me.ObjectContext.ThingsToDo
    End Function

    Public Sub InsertThingToDo(ByVal ThingToDo As ThingToDo)
        If ((ThingToDo.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(ThingToDo, EntityState.Added)
        Else
            Me.ObjectContext.ThingsToDo.AddObject(ThingToDo)
        End If
    End Sub

    Public Sub UpdateThingToDo(ByVal currentThingToDo As ThingToDo)
        Me.ObjectContext.ThingsToDo.AttachAsModified(currentThingToDo, Me.ChangeSet.GetOriginal(currentThingToDo))
    End Sub

    Public Sub DeleteThingToDo(ByVal ThingToDo As ThingToDo)
        If ((ThingToDo.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(ThingToDo, EntityState.Deleted)
        Else
            Me.ObjectContext.ThingsToDo.Attach(ThingToDo)
            Me.ObjectContext.ThingsToDo.DeleteObject(ThingToDo)
        End If
    End Sub

    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'Hostals'.
    Public Function GetNotes() As IQueryable(Of Nota)
        Return Me.ObjectContext.Notes
    End Function

    Public Function GetNotesNoCaducadesPerUsuari(IdUsuari As Integer, DataActual As Date) As IQueryable(Of Nota)
        Dim vUsuari As Usuari = (From U As Usuari In ObjectContext.Usuaris.Include("UsuariHostals") Where U.Id = IdUsuari).FirstOrDefault
        Dim LListaIdHostalAssignats As List(Of Integer) = (From UH As UsuariHostal In vUsuari.UsuariHostals Select UH.IdHostal).ToList
        DataActual = DataActual.ToUniversalTime

        Return (From N As Nota In Me.ObjectContext.Notes
                Where _
                    N.DataCaducitat >= DataActual _
                    AndAlso ( _
                        vUsuari.IdTipusUsuari = EnumTipusUsuari.Administrador _
                        OrElse N.IdUsuariCreador = vUsuari.Id _
                        OrElse (N.IdUsuariDesti.HasValue AndAlso N.IdUsuariDesti = vUsuari.Id) _
                        OrElse (Not N.IdUsuariDesti.HasValue AndAlso Not N.IdHostalDesti.HasValue) _
                        OrElse (Not N.IdUsuariDesti.HasValue AndAlso N.IdHostalDesti.HasValue AndAlso LListaIdHostalAssignats.Contains(N.IdHostalDesti.Value)) _
                    )).AsQueryable


    End Function

    Public Sub InsertNota(ByVal nota As Nota)
        If ((nota.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(nota, EntityState.Added)
        Else
            Me.ObjectContext.Notes.AddObject(nota)
        End If
    End Sub

    Public Sub UpdateNota(ByVal currentNota As Nota)
        Me.ObjectContext.Notes.AttachAsModified(currentNota, Me.ChangeSet.GetOriginal(currentNota))
    End Sub

    Public Sub DeleteNota(ByVal nota As Nota)
        If ((nota.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(nota, EntityState.Deleted)
        Else
            Me.ObjectContext.Notes.Attach(nota)
            Me.ObjectContext.Notes.DeleteObject(nota)
        End If
    End Sub


    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'LLibresCaixa'.
    Public Function GetNeteges() As IQueryable(Of Neteja)
        Return Me.ObjectContext.Neteges
    End Function

    Public Function GetNetejaObertaHostal(IdHostal As Integer, Data As Date, IdUsuariNeteja As Integer) As IQueryable(Of Neteja)
        Data = Data.ToUniversalTime

        Return (From N As Neteja In Me.ObjectContext.Neteges _
        Where _
            N.IdHostal = IdHostal _
            AndAlso (IdUsuariNeteja = -1 OrElse N.IdUsuariNeteja = IdUsuariNeteja) _
            AndAlso N.Data = Data _
            AndAlso Not N.IdUsuariTancament.HasValue).AsQueryable

    End Function

    Public Function GetNetegesPerHostalUsuariIDates(Hostals As List(Of Integer), IdUsuari As Integer, DataInicial As Nullable(Of Date), DataFinal As Nullable(Of Date)) As IQueryable(Of Neteja)
        'Dim logWriter As IO.StreamWriter = System.IO.File.CreateText("E:\web\vetaquic\Lullaby\bin\logs.txt")
        'logWriter.WriteLine(DataInicial.Value)
        'logWriter.WriteLine(DataFinal.Value)
        'logWriter.WriteLine(DataFinal.Value.Kind)

        If DataInicial.HasValue Then DataInicial = DataInicial.Value.ToUniversalTime ' Date.SpecifyKind(DataInicial.Value.Date, Global.System.DateTimeKind.Unspecified)
        If DataFinal.HasValue Then DataFinal = DataFinal.Value.ToUniversalTime 'Date.SpecifyKind(DataFinal.Value.Date, Global.System.DateTimeKind.Unspecified)

        'logWriter.WriteLine(DataInicial.Value)
        'logWriter.WriteLine(DataFinal.Value)
        'logWriter.WriteLine(DataFinal.Value.Kind)
        'logWriter.WriteLine("-------------------------------------")
        'logWriter.Close()


        Return (From N As Neteja In Me.ObjectContext.Neteges _
                Where _
                    (Hostals.Contains(N.IdHostal) OrElse Hostals.Contains(-1)) _
                    AndAlso (IdUsuari = -1 OrElse N.IdUsuariNeteja = IdUsuari) _
                    AndAlso (Not DataInicial.HasValue OrElse N.Data >= DataInicial) _
                    AndAlso (Not DataFinal.HasValue OrElse N.Data <= DataFinal)).AsQueryable()
    End Function

    Public Sub InsertNeteja(ByVal Neteja As Neteja)
        If ((Neteja.EntityState = EntityState.Detached) _
            = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(Neteja, EntityState.Added)
        Else
            Me.ObjectContext.Neteges.AddObject(Neteja)
        End If
        Neteja.Data = Neteja.Data.ToUniversalTime
    End Sub

    Public Sub UpdateNeteja(ByVal currentNeteja As Neteja)
        Me.ObjectContext.Neteges.AttachAsModified(currentNeteja, Me.ChangeSet.GetOriginal(currentNeteja))
    End Sub

    Public Sub DeleteNeteja(ByVal Neteja As Neteja)
        If ((Neteja.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(Neteja, EntityState.Deleted)
        Else
            Me.ObjectContext.Neteges.Attach(Neteja)
            Me.ObjectContext.Neteges.DeleteObject(Neteja)
        End If
    End Sub

    Public Function GetDocuments() As IQueryable(Of Document)
        Return Me.ObjectContext.Documents
    End Function

    Public Function GetDocumentsPerHostalIDates(IdHostal As Integer, DataInicial As Nullable(Of Date), DataFinal As Nullable(Of Date)) As IQueryable(Of Document)
        'Dim logWriter As IO.StreamWriter = System.IO.File.CreateText("E:\web\vetaquic\Lullaby\bin\logs.txt")
        'logWriter.WriteLine(DataInicial.Value)
        'logWriter.WriteLine(DataFinal.Value)
        'logWriter.WriteLine(DataFinal.Value.Kind)

        If DataInicial.HasValue Then DataInicial = DataInicial.Value.ToUniversalTime ' Date.SpecifyKind(DataInicial.Value.Date, Global.System.DateTimeKind.Unspecified)
        If DataFinal.HasValue Then DataFinal = DataFinal.Value.ToUniversalTime 'Date.SpecifyKind(DataFinal.Value.Date, Global.System.DateTimeKind.Unspecified)

        'logWriter.WriteLine(DataInicial.Value)
        'logWriter.WriteLine(DataFinal.Value)
        'logWriter.WriteLine(DataFinal.Value.Kind)
        'logWriter.WriteLine("-------------------------------------")
        'logWriter.Close()


        Return (From N As Document In Me.ObjectContext.Documents _
                Where _
                    (IdHostal = -1 OrElse N.IdHostal = IdHostal) _
                    AndAlso (Not DataInicial.HasValue OrElse N.DataInicial >= DataInicial) _
                    AndAlso (Not DataFinal.HasValue OrElse N.DataInicial <= DataFinal)).AsQueryable()
    End Function

    Public Sub InsertDocument(ByVal Document As Document)
        If ((Document.EntityState = EntityState.Detached) _
            = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(Document, EntityState.Added)
        Else
            Me.ObjectContext.Documents.AddObject(Document)
        End If
        Document.DataInicial = Document.DataInicial.ToUniversalTime
        Document.DataFinal = Document.DataFinal.ToUniversalTime
    End Sub

    Public Sub UpdateDocument(ByVal currentDocument As Document)
        Me.ObjectContext.Documents.AttachAsModified(currentDocument, Me.ChangeSet.GetOriginal(currentDocument))
        currentDocument.DataInicial = currentDocument.DataInicial.ToUniversalTime
        currentDocument.DataFinal = currentDocument.DataFinal.ToUniversalTime
    End Sub

    Public Sub DeleteDocument(ByVal Document As Document)
        If ((Document.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(Document, EntityState.Deleted)
        Else
            Me.ObjectContext.Documents.Attach(Document)
            Me.ObjectContext.Documents.DeleteObject(Document)
        End If
    End Sub

    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'LLibresCaixa'.
    Public Function GetLLibresCaixa() As IQueryable(Of LLibreCaixa)
        Return Me.ObjectContext.LLibresCaixa
    End Function

    Public Function GetFullsDeCaixaPerHostalUsuariIDates(IdHostal As Integer, IdUsuari As Integer, DataInicial As Nullable(Of Date), DataFinal As Nullable(Of Date)) As IQueryable(Of LLibreCaixa)
        'Dim logWriter As IO.StreamWriter = System.IO.File.CreateText("E:\web\vetaquic\Lullaby\bin\logs.txt")
        'logWriter.WriteLine(DataInicial.Value)
        'logWriter.WriteLine(DataFinal.Value)
        'logWriter.WriteLine(DataFinal.Value.Kind)

        If DataInicial.HasValue Then DataInicial = DataInicial.Value.ToUniversalTime ' Date.SpecifyKind(DataInicial.Value.Date, Global.System.DateTimeKind.Unspecified)
        If DataFinal.HasValue Then DataFinal = DataFinal.Value.ToUniversalTime 'Date.SpecifyKind(DataFinal.Value.Date, Global.System.DateTimeKind.Unspecified)

        'logWriter.WriteLine(DataInicial.Value)
        'logWriter.WriteLine(DataFinal.Value)
        'logWriter.WriteLine(DataFinal.Value.Kind)
        'logWriter.WriteLine("-------------------------------------")
        'logWriter.Close()


        Return (From LL As LLibreCaixa In Me.ObjectContext.LLibresCaixa.Include("LLibreCaixaDespesaIngres.TipusDespesaIngres").Include("Reserva") _
                Where _
                    (IdHostal = -1 OrElse LL.IdHostal = IdHostal) _
                    AndAlso (IdUsuari = -1 OrElse LL.IdUsuari = IdUsuari) _
                    AndAlso (Not DataInicial.HasValue OrElse LL.Data >= DataInicial) _
                    AndAlso (Not DataFinal.HasValue OrElse LL.Data <= DataFinal)).AsQueryable()
    End Function

    Public Sub InsertLLibreCaixa(ByVal LLibreCaixa As LLibreCaixa)
        Using Entities As New LullabyEntities
            Dim LLibreIgual As LLibreCaixa = (From ll As LLibreCaixa In Entities.LLibresCaixa Where ll.IdUsuari = LLibreCaixa.IdUsuari AndAlso ll.IdHostal = LLibreCaixa.IdHostal Order By ll.Id Descending).FirstOrDefault
            If LLibreIgual IsNot Nothing AndAlso Not LLibreIgual.EsTancat Then
                Dim Err As New ValidationResult(String.Format(My.Resources.StringLibrary.JaHiHaUnLLibreObert, Right("00" & LLibreIgual.Data.Day, 2) & "/" & Right("00" & LLibreIgual.Data.Month, 2) & "/" & Right("0000" & LLibreIgual.Data.Year, 4)))
                Throw New ValidationException(Err, Nothing, Nothing)
            End If

            If LLibreCaixa.ControlarLLibreObertAnterior Then
                Dim LLibreObertAnterior As LLibreCaixa = (From ll As LLibreCaixa In Entities.LLibresCaixa.Include("Usuari") Where Not ll.DataHoraTancament.HasValue AndAlso ll.IdHostal = LLibreCaixa.IdHostal Order By ll.Id Descending).FirstOrDefault
                If LLibreObertAnterior IsNot Nothing Then
                    Dim Err As New ValidationResult(String.Format(My.Resources.StringLibrary.JaHiHaUnLLibreObertAnterior, LLibreObertAnterior.Usuari.Nom, Right("00" & LLibreObertAnterior.Data.Day, 2) & "/" & Right("00" & LLibreObertAnterior.Data.Month, 2) & "/" & Right("0000" & LLibreObertAnterior.Data.Year, 4)), New List(Of String)({"ControlarLLibreObertAnterior"}))
                    Throw New ValidationException(Err, Nothing, Nothing)
                End If
            End If
        End Using

        If ((LLibreCaixa.EntityState = EntityState.Detached) _
            = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(LLibreCaixa, EntityState.Added)
        Else
            Me.ObjectContext.LLibresCaixa.AddObject(LLibreCaixa)
        End If
    End Sub

    Public Sub UpdateLLibreCaixa(ByVal currentLLibreCaixa As LLibreCaixa)
        Me.ObjectContext.LLibresCaixa.AttachAsModified(currentLLibreCaixa, Me.ChangeSet.GetOriginal(currentLLibreCaixa))
    End Sub

    Public Sub DeleteLLibreCaixa(ByVal lLibreCaixa As LLibreCaixa)
        If ((lLibreCaixa.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(lLibreCaixa, EntityState.Deleted)
        Else
            Me.ObjectContext.LLibresCaixa.Attach(lLibreCaixa)
            Me.ObjectContext.LLibresCaixa.DeleteObject(lLibreCaixa)
        End If
    End Sub

    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'LLibreCaixaDespesaIngres'.
    Public Function GetLLibreCaixaDespesaIngres() As IQueryable(Of LLibreCaixaDespesaIngres)
        Return Me.ObjectContext.LLibreCaixaDespesaIngres
    End Function

    Public Sub InsertLLibreCaixaDespesaIngres(ByVal lLibreCaixaDespesaIngres As LLibreCaixaDespesaIngres)
        If ((lLibreCaixaDespesaIngres.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(lLibreCaixaDespesaIngres, EntityState.Added)
        Else
            Me.ObjectContext.LLibreCaixaDespesaIngres.AddObject(lLibreCaixaDespesaIngres)
        End If
    End Sub

    Public Sub UpdateLLibreCaixaDespesaIngres(ByVal currentLLibreCaixaDespesaIngres As LLibreCaixaDespesaIngres)
        Me.ObjectContext.LLibreCaixaDespesaIngres.AttachAsModified(currentLLibreCaixaDespesaIngres, Me.ChangeSet.GetOriginal(currentLLibreCaixaDespesaIngres))
    End Sub

    Public Sub DeleteLLibreCaixaDespesaIngres(ByVal lLibreCaixaDespesaIngres As LLibreCaixaDespesaIngres)
        If ((lLibreCaixaDespesaIngres.EntityState = EntityState.Detached) = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(lLibreCaixaDespesaIngres, EntityState.Deleted)
        Else
            Me.ObjectContext.LLibreCaixaDespesaIngres.Attach(lLibreCaixaDespesaIngres)
            Me.ObjectContext.LLibreCaixaDespesaIngres.DeleteObject(lLibreCaixaDespesaIngres)
        End If
    End Sub

    Public Function GetReserva() As IQueryable(Of Reserva)
        Return Me.ObjectContext.Reserves
    End Function

    Public Sub InsertReserva(ByVal Reserva As Reserva)
        If ((Reserva.EntityState = EntityState.Detached) = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(Reserva, EntityState.Added)
        Else
            Me.ObjectContext.Reserves.AddObject(Reserva)
        End If
    End Sub

    Public Sub UpdateReserva(ByVal currentReserva As Reserva)
        Me.ObjectContext.Reserves.AttachAsModified(currentReserva, Me.ChangeSet.GetOriginal(currentReserva))
    End Sub

    Public Sub DeleteReserva(ByVal Reserva As Reserva)
        If ((Reserva.EntityState = EntityState.Detached) = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(Reserva, EntityState.Deleted)
        Else
            Me.ObjectContext.Reserves.Attach(Reserva)
            Me.ObjectContext.Reserves.DeleteObject(Reserva)
        End If
    End Sub

    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'TipusDespesaIngres'.
    Public Function GetTipusDespesaIngres() As IQueryable(Of TipusDespesaIngres)
        Return Me.ObjectContext.TipusDespesaIngres
    End Function

    Public Function GetTipusDespesaIngresActius() As IQueryable(Of TipusDespesaIngres)
        Return Me.ObjectContext.TipusDespesaIngres.Where(Function(f) f.EsBaixa = False)
    End Function

    Public Sub InsertTipusDespesaIngres(ByVal tipusDespesaIngres As TipusDespesaIngres)
        If ((tipusDespesaIngres.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(tipusDespesaIngres, EntityState.Added)
        Else
            Me.ObjectContext.TipusDespesaIngres.AddObject(tipusDespesaIngres)
        End If
    End Sub

    Public Sub UpdateTipusDespesaIngres(ByVal currentTipusDespesaIngres As TipusDespesaIngres)
        Me.ObjectContext.TipusDespesaIngres.AttachAsModified(currentTipusDespesaIngres, Me.ChangeSet.GetOriginal(currentTipusDespesaIngres))
    End Sub

    Public Sub DeleteTipusDespesaIngres(ByVal tipusDespesaIngres As TipusDespesaIngres)
        If ((tipusDespesaIngres.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(tipusDespesaIngres, EntityState.Deleted)
        Else
            Me.ObjectContext.TipusDespesaIngres.Attach(tipusDespesaIngres)
            Me.ObjectContext.TipusDespesaIngres.DeleteObject(tipusDespesaIngres)
        End If
    End Sub


    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'Usuaris'.
    Public Function GetUsuaris() As IQueryable(Of Usuari)
        Return Me.ObjectContext.Usuaris.Include("UsuariHostals").Include("UsuariReports")
    End Function

    Public Function GetUsuariByNamePassword(ByVal UserName As String, ByVal Password As String) As Usuari
        Return Me.ObjectContext.Usuaris.Include("UsuariHostals").Include("UsuariReports").Where(Function(f) f.UserName = UserName And f.Password = Password).FirstOrDefault()
    End Function

    Public Sub InsertUsuari(ByVal usuari As Usuari)
        If ((usuari.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(usuari, EntityState.Added)
        Else
            Me.ObjectContext.Usuaris.AddObject(usuari)
        End If
    End Sub

    Public Sub UpdateUsuari(ByVal currentUsuari As Usuari)
        Me.ObjectContext.Usuaris.AttachAsModified(currentUsuari, Me.ChangeSet.GetOriginal(currentUsuari))
    End Sub

    Public Sub DeleteUsuari(ByVal usuari As Usuari)
        If ((usuari.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(usuari, EntityState.Deleted)
        Else
            Me.ObjectContext.Usuaris.Attach(usuari)
            Me.ObjectContext.Usuaris.DeleteObject(usuari)
        End If
    End Sub

    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'UsuarisHostals'.
    Public Function GetUsuarisHostals() As IQueryable(Of UsuariHostal)
        Return Me.ObjectContext.UsuarisHostals
    End Function

    Public Sub InsertUsuariHostal(ByVal usuariHostal As UsuariHostal)
        If ((usuariHostal.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(usuariHostal, EntityState.Added)
        Else
            Me.ObjectContext.UsuarisHostals.AddObject(usuariHostal)
        End If
    End Sub

    Public Sub UpdateUsuariHostal(ByVal currentUsuariHostal As UsuariHostal)
        Me.ObjectContext.UsuarisHostals.AttachAsModified(currentUsuariHostal, Me.ChangeSet.GetOriginal(currentUsuariHostal))
    End Sub

    Public Sub DeleteUsuariHostal(ByVal usuariHostal As UsuariHostal)
        If ((usuariHostal.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(usuariHostal, EntityState.Deleted)
        Else
            Me.ObjectContext.UsuarisHostals.Attach(usuariHostal)
            Me.ObjectContext.UsuarisHostals.DeleteObject(usuariHostal)            
        End If
    End Sub

    'TODO:
    ' Considere la posibilidad de restringir los resultados de su método de consulta. Si necesita entradas adicionales, puede
    ' agregar parámetros a este método o crear métodos de consulta adicionales con distintos nombres.
    'Para admitir la paginación tendrá que agregar ordenación a la consulta 'UsuarisHostals'.
    Public Function GetUsuarisReports() As IQueryable(Of UsuariReport)
        Return Me.ObjectContext.UsuarisReports
    End Function

    Public Sub InsertUsuariReport(ByVal UsuariReport As UsuariReport)
        If ((UsuariReport.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(UsuariReport, EntityState.Added)
        Else
            Me.ObjectContext.UsuarisReports.AddObject(UsuariReport)
        End If
    End Sub

    Public Sub UpdateUsuariReport(ByVal currentUsuariReport As UsuariReport)
        Me.ObjectContext.UsuarisReports.AttachAsModified(currentUsuariReport, Me.ChangeSet.GetOriginal(currentUsuariReport))
    End Sub

    Public Sub DeleteUsuariReport(ByVal UsuariReport As UsuariReport)
        If ((UsuariReport.EntityState = EntityState.Detached) _
                    = False) Then
            Me.ObjectContext.ObjectStateManager.ChangeObjectState(UsuariReport, EntityState.Deleted)
        Else
            Me.ObjectContext.UsuarisReports.Attach(UsuariReport)
            Me.ObjectContext.UsuarisReports.DeleteObject(UsuariReport)
        End If
    End Sub



#Region "Login"

    Private Shared Function DefaultUser() As User
        Dim Usuari As User = New User
        Usuari.Name = String.Empty

        Return Usuari
    End Function

    Public Function Login(ByVal userName As String, ByVal password As String, ByVal isPersistent As Boolean, ByVal customData As String) As User Implements ApplicationServices.IAuthentication(Of User).Login
        If (Me.ValidateUser(userName, password)) Then
            Dim Usuari As Usuari = Me.ObjectContext.Usuaris.Include("UsuariHostals.Hostal").Include("UsuariReports").Where(Function(f) f.UserName = userName And f.Password = password).FirstOrDefault()
            Dim user As User = Me.GetUser(userName)

            If Usuari.IdTipusUsuari <> EnumTipusUsuari.Administrador AndAlso Usuari.IdTipusUsuari <> EnumTipusUsuari.Manager AndAlso (From UH As UsuariHostal In Usuari.UsuariHostals Where UH.Hostal.Ip = customData Select UH.Hostal).FirstOrDefault() Is Nothing Then
                user.hasIpPermision = False
            Else
                user.hasIpPermision = True
            End If

            System.Web.Security.FormsAuthentication.SetAuthCookie(userName, isPersistent)
            Return user
        Else
            Return (Nothing)
        End If
    End Function

    Private Function ValidateUser(ByVal username As String, ByVal password As String) As Boolean
        Dim Usuari As Usuari = Me.ObjectContext.Usuaris.Where(Function(f) f.UserName = username And f.Password = password).FirstOrDefault()
        If Usuari Is Nothing Then
            Return False
        Else
            Return True
        End If
    End Function

    Public Function Logout() As User Implements ApplicationServices.IAuthentication(Of User).Logout
        System.Web.Security.FormsAuthentication.SignOut()
        Return DefaultUser()
    End Function

    Public Function GetUser() As User Implements ApplicationServices.IAuthentication(Of LullabyFullDeCaixa.Web.User).GetUser
        If ((Me.ServiceContext IsNot Nothing) AndAlso (Me.ServiceContext.User IsNot Nothing) AndAlso Me.ServiceContext.User.Identity.IsAuthenticated) Then
            Return Me.GetUser(Me.ServiceContext.User.Identity.Name)
        End If

        Return LullabyDomainService.DefaultUser()
    End Function

    Private Function GetUser(ByVal username As String) As User
        Dim Usuari As Usuari = (From U As Usuari In Me.ObjectContext.Usuaris Where U.UserName = username).FirstOrDefault
        If Usuari IsNot Nothing Then
            Dim user As User = New User
            user.Name = Usuari.Nom
            Return user
        Else
            Return Nothing
        End If
    End Function

    Public Sub UpdateUser(ByVal currentUsuari As User) Implements ApplicationServices.IAuthentication(Of User).UpdateUser
        ' Ensure the user data that will be modified represents the currently
        ' authenticated identity 
        If ((Me.ServiceContext.User Is Nothing) OrElse (Me.ServiceContext.User.Identity Is Nothing) OrElse Not String.Equals(Me.ServiceContext.User.Identity.Name, currentUsuari.Name, System.StringComparison.Ordinal)) Then
            Throw New UnauthorizedAccessException("You are only authorized to modify your own profile.")
        End If

        'Me.ObjectContext.Usuari.AttachAsModified(currentUsuari, Me.ChangeSet.GetOriginal(currentUsuari))
    End Sub

#End Region

End Class


Public Class User
    Implements ApplicationServices.IUser

    Private _Nom As String

    <Key()> _
    <Global.System.Runtime.Serialization.DataMemberAttribute()> _
    Public Property Name As String Implements System.ServiceModel.DomainServices.Server.ApplicationServices.IUser.Name
        Get
            Return _Nom
        End Get
        Set(ByVal value As String)
            _Nom = value
        End Set
    End Property

    Private _hasIpPermision As Boolean = False
    <Global.System.Runtime.Serialization.DataMemberAttribute()> _
    Public Property hasIpPermision As Boolean
        Get
            Return _hasIpPermision
        End Get
        Set(ByVal value As Boolean)
            _hasIpPermision = value
        End Set
    End Property

    <Global.System.Runtime.Serialization.DataMemberAttribute()> _
    Public Property Roles As System.Collections.Generic.IEnumerable(Of String) Implements System.ServiceModel.DomainServices.Server.ApplicationServices.IUser.Roles
        Get
            Return Nothing
        End Get
        Set(ByVal value As System.Collections.Generic.IEnumerable(Of String))

        End Set
    End Property
End Class
